/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.muni.fi.pa036is.validators;

import cz.muni.fi.pa036is.dto.SeasonFormTO;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

/**
 *
 * @author jostri
 */
public class SeasonValidator implements Validator {
    
    @Override
    public boolean supports(Class<?> c) {
        return SeasonFormTO.class.isAssignableFrom(c);
    }

    @Override
    public void validate(Object o, Errors errors) {
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name", "name.empty", "Name of season is required.");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "startDate", "startDate.empty", "Start date is required.");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "endDate", "endDate.empty", "End date is required.");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "admissionPrice", "admissionPrice.empty", "Admission price is required.");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "victoryCondition", "victoryCondition.empty", "Victory condition is required.");
        
        SeasonFormTO season = (SeasonFormTO) o;
        
        if (season.getVictoryCondition() == 1) {
            ValidationUtils.rejectIfEmptyOrWhitespace(errors, "pointsForWin", "pointsForWin.empty", "Points for win of match are required.");
            ValidationUtils.rejectIfEmptyOrWhitespace(errors, "pointsForDraw", "pointsForDraw.empty", "Points for draw of match are required.");
            ValidationUtils.rejectIfEmptyOrWhitespace(errors, "pointsForLose", "pointsForLose.empty", "Points for lose of match are required.");
        }
        
        
        
        if (season.getStartDate().after(season.getEndDate())) {
            errors.rejectValue("endDate", "End date should be before start date.");
        }
        
        if (season.getVictoryCondition() == 1) {
            if (season.getPointsForWin() < 0) {
                errors.rejectValue("pointsForWin", "Points for win should be more than or equal to 0.");
            }

            if (season.getPointsForDraw()< 0) {
                errors.rejectValue("pointsForWin", "Points for draw should be more than or equal to 0.");
            }

            if (season.getPointsForLose()< 0) {
                errors.rejectValue("pointsForWin", "Points for lose should be more than or equal to 0.");
            }
        }
        
        if (season.getName().length() > 100) {
            errors.rejectValue("name", "Max length of name is 100 characters.");
        }
    }
    
}
